//
//  SearchController.m
//  takeout
//
//  Created by Mac on 12-5-16.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "SearchController.h"
#define addComponent 0
#define typeComponent 1
#define timeComponent 2
#import "SearchShopListController.h"
#import "SupplierCategory.h"


@implementation SearchController
@synthesize appDelegate;
@synthesize searchBarCustom;
@synthesize directBtn;
@synthesize detailBtn;
@synthesize directSearchView;
@synthesize detailSearchView;
@synthesize address;
@synthesize time;
@synthesize isSelling;
@synthesize addTestData;
@synthesize typeTestData;
@synthesize timeTestData;
@synthesize isTouched;

-(void)initSearchBtn{
    //设置搜索按钮背景
    UIImageView *topView=[[UIImageView alloc]init];
    topView.frame=CGRectMake(0,-5,320, 37);
    NSString *filePath=[[NSBundle mainBundle] pathForResource:@"searchTypeBg" ofType:@"png"];
    [topView setImage:[UIImage imageWithContentsOfFile:filePath]];  
    [topView setUserInteractionEnabled:YES];  
    [self.view addSubview:topView];
    //设置搜索按钮
    directBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    directBtn.frame=CGRectMake(0, -5, 159, 37);
    [directBtn setTitle:@"直接搜索" forState:UIControlStateNormal];
    directBtn.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:14];
    NSString *filePath2=[[NSBundle mainBundle] pathForResource:@"typeLeftG" ofType:@"png"];
    [directBtn setBackgroundImage:[UIImage imageWithContentsOfFile:filePath2] forState:UIControlStateNormal];
    NSString *filePath3=[[NSBundle mainBundle] pathForResource:@"typeLeftY" ofType:@"png"];
    [directBtn setBackgroundImage:[UIImage imageWithContentsOfFile:filePath3] forState:UIControlStateSelected];
    directBtn.selected=YES;
    [directBtn addTarget:self action:@selector(directSearch:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:directBtn];
    detailBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    detailBtn.frame=CGRectMake(159, -5, 159, 37);
    [detailBtn setTitle:@"进阶搜索" forState:UIControlStateNormal];
    detailBtn.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:14];
    NSString *filePath4=[[NSBundle mainBundle] pathForResource:@"typeRightG" ofType:@"png"];
    [detailBtn setBackgroundImage:[UIImage imageWithContentsOfFile:filePath4] forState:UIControlStateNormal];
    NSString *filePath5=[[NSBundle mainBundle] pathForResource:@"typeRightY" ofType:@"png"];
    [detailBtn setBackgroundImage:[UIImage imageWithContentsOfFile:filePath5] forState:UIControlStateSelected];
    [detailBtn addTarget:self action:@selector(detailSearch:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:detailBtn];
}
-(void)initSearchCon{
    //设置直接搜索内容背景
    directSearchView=[[UIView alloc]initWithFrame:CGRectMake(0,44, 320, 44)];
    [self.view addSubview:directSearchView];
    //设置直接搜索控件
    searchBarCustom = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; 
    searchBarCustom.delegate=self;
    //添加文本默认内容
    searchBarCustom.placeholder=@"请输入商铺名称或菜品"; 
    //移出原背景颜色
    UIView *segment=[searchBarCustom.subviews objectAtIndex:0];
    [segment removeFromSuperview];
    [directSearchView addSubview:searchBarCustom];
    //设置详细搜索内容背景
    detailSearchView=[[UIView alloc]initWithFrame:CGRectMake(0,90,320,300)];
    [self.view addSubview:detailSearchView];
    [detailSearchView setHidden:YES];
    //设置条件标题
    UILabel *addLbl=[[UILabel alloc]initWithFrame:CGRectMake(40,-20,70, 16)];
    [addLbl setFont:[UIFont fontWithName:@"Helvetica-Bold" size:16]];
    [addLbl setBackgroundColor:[UIColor clearColor]];
    addLbl.text=@"周边地区";
    [detailSearchView addSubview:addLbl];
    
    UILabel *typeLbl=[[UILabel alloc]initWithFrame:CGRectMake(140,-20,45, 16)];
    [typeLbl setFont:[UIFont fontWithName:@"Helvetica-Bold" size:16]];
    [typeLbl setBackgroundColor:[UIColor clearColor]];
    typeLbl.text=@"类型";
    [detailSearchView addSubview:typeLbl];
    
    UILabel *timeLbl=[[UILabel alloc]initWithFrame:CGRectMake(215,-20,80, 16)];
    [timeLbl setFont:[UIFont fontWithName:@"Helvetica-Bold" size:16]];
    [timeLbl setBackgroundColor:[UIColor clearColor]];
    timeLbl.text=@"营业时间";
    [detailSearchView addSubview:timeLbl];
    
    //设置pickerview
    UIPickerView *conditionPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(20, 12, 280, 200)];
    conditionPickerView.delegate = self;
    conditionPickerView.dataSource = self;
    conditionPickerView.showsSelectionIndicator = YES;
    [detailSearchView addSubview:conditionPickerView];
    //设置确定按钮
    UIButton *searchBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame=CGRectMake(95, 210, 130, 40);
    
    NSString *filePath=[[NSBundle mainBundle] pathForResource:@"searchBg03" ofType:@"png"];
    [searchBtn setBackgroundImage:[UIImage imageWithContentsOfFile:filePath] forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(detailSearchListDelay:) forControlEvents:UIControlEventTouchUpInside];
    [detailSearchView addSubview:searchBtn];
    
}

- (void)viewDidLoad
{   
    [super viewDidLoad];
    self.title=@"搜索";
//    NSInteger currentPage=1;
    //初始化
    appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//	manager=[[SupplierManager alloc]init];
    //    fmdbSupplierManager=[[FMDBSupplierManager alloc]init];
    //设置导航背景颜色
    NSString *filePath=[[NSBundle mainBundle] pathForResource:@"searchBarBg" ofType:@"png"];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithContentsOfFile:filePath] forBarMetrics: UIBarMetricsDefault];
    //设置背景颜色
    self.view.backgroundColor=[UIColor groupTableViewBackgroundColor];
    //设置背景按钮
    UIButton *bgBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    bgBtn.frame=CGRectMake(0,0,320, 460);
    [bgBtn addTarget:self action:@selector(cancelInput:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:bgBtn];
    //初始化搜索按钮
    [self initSearchBtn];
    //初始化不同搜索类型显示的不同view
    [self initSearchCon];
    //测试数据
    addTestData = [[NSArray alloc] initWithObjects:@"周边地区",@"市政府", @"步行街",@"狮标",@"鸳鸯池",@"华侨医院",@"服装城", nil];
    timeTestData= [[NSArray alloc] initWithObjects:@"营业状况",@"营业中",@"打烊", nil];
    typeTestData=[[NSMutableArray alloc]initWithObjects:@"类型",nil];
    NSArray *supplierCategoriess = [appDelegate.recieveDictionary objectForKey:@"SupplierCategories"];
    for(SupplierCategory *supplierCategory in supplierCategoriess){
        [typeTestData addObject:supplierCategory.supplierCategoryName];
    }
    appDelegate.supId=nil;
    isSelling =nil;
    address=nil;
//    type=nil;
    time=nil;
}

- (void)viewWillAppear:(BOOL)animated{
    isTouched=YES;
}

//取消键盘
- (IBAction)cancelInput:(id)sender{
    [searchBarCustom resignFirstResponder];
}

-(IBAction)detailSearchListDelay:(id)sender{
    [self performSelector:@selector(detailSearchList:) withObject:sender afterDelay:0.1];
}

//进阶搜索
-(IBAction)detailSearchList:(id)sender{
    
    if(isTouched){
        
        isTouched=NO;
        NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
        SystemSoundID system_sound_id;
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
        AudioServicesPlaySystemSound(system_sound_id);
        
        if([address isEqualToString: @"周边地区"]){
            address = nil;
        }
//        if([type isEqualToString:@"类型"]){
//            type=nil;
//        }
        if([time isEqualToString: @"营业中"]){
            isSelling = @"y";
        }
        else if([time isEqualToString: @"打烊"]){
            isSelling = @"n";
        }
        else{
            isSelling = nil;
        }
//        if([appDelegate status]){
//            //联网
//            suppliers = [[manager getSupplier:appDelegate.supId pageIndex:currentPage road:address isSelling:isSelling] retain];
//        }
//        //    else{
//        //        //离线
//        //        suppliers=[[fmdbSupplierManager getSupplierByCategoryIdAndPageFromLoc:appDelegate.supId sPage:@"1" road:address isSelling:isSelling] retain];
//        //    }
//        if (suppliers.count==0) {
//            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"没有该类型的商家" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
//            [alertView show];
//            [alertView release];
//            return;
//        }
        
        //创建新的试图并将试图推入栈中
        SearchShopListController *shopListController = [[SearchShopListController alloc]init];
        NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:2];
        shopListController.address=address;
        shopListController.isSelling=isSelling;
        shopListController.searchType=@"1";//进入详细搜索
        [shopListController setRecieveDictionary:dictionary];
        [self.navigationController pushViewController: shopListController animated:YES];
    }
}

//点击直接搜索
-(IBAction)directSearch:(id)sender{
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    
    directBtn.selected=YES;
    detailBtn.selected=NO;
    [directSearchView setHidden:NO];
    [detailSearchView setHidden:YES];
}

//点击详细搜索
-(IBAction)detailSearch:(id)sender{
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    
    [searchBarCustom resignFirstResponder];
    directBtn.selected=NO;
    detailBtn.selected=YES;
    [directSearchView setHidden:YES];
    [detailSearchView setHidden:NO];
}

//返回有pickerview的组件数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 3;
}

//返回每个组件上的行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if(component==addComponent){
        return [addTestData count];     
    }
    if(component==typeComponent){
        return [typeTestData count];     
    }
    return [timeTestData count];     
}

//设置picker的值和字体大小
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *contentLbl = nil;      
    if (component == addComponent) {
        
        contentLbl = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 100, 30)];
        contentLbl.textAlignment = UITextAlignmentCenter;
        contentLbl.font = [UIFont systemFontOfSize:14];
        contentLbl.text=[addTestData objectAtIndex:row];
        contentLbl.backgroundColor = [UIColor clearColor];
    }
    if(component==typeComponent){
        contentLbl = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 100, 30)];
        contentLbl.textAlignment = UITextAlignmentCenter;
        contentLbl.font = [UIFont systemFontOfSize:14];
        contentLbl.text=[typeTestData objectAtIndex:row];
        contentLbl.backgroundColor = [UIColor clearColor];
    }
    if(component==timeComponent){
        contentLbl = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 100, 30)];
        contentLbl.textAlignment = UITextAlignmentCenter;
        contentLbl.font = [UIFont systemFontOfSize:14];  
        contentLbl.text=[timeTestData objectAtIndex:row];
        contentLbl.backgroundColor = [UIColor clearColor];
    }
    return contentLbl;
}

//当你选中pickerview的某行时会调用该函数。
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    NSArray *supplierCategories = [appDelegate.recieveDictionary objectForKey:@"SupplierCategories"];
    if (component == addComponent) {
        address=[addTestData objectAtIndex:row];
    }
    if (component == typeComponent) {
//        type=[typeTestData objectAtIndex:row];
        if(row==0){
            appDelegate.supId=nil;
        }
        else{
            SupplierCategory *supplierCategory=[supplierCategories objectAtIndex:row-1];
            appDelegate.supId=[NSString stringWithFormat: @"%d", supplierCategory.supplierCategoryId];
        }
    }
    if (component == timeComponent) {
        time=[timeTestData objectAtIndex:row];
    }
}

//直接搜索按钮
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar { 
    //创建新的试图并将试图推入栈中
    SearchShopListController *shopListController = [[SearchShopListController alloc]init];
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:1];
    shopListController.searchType=@"0";
    shopListController.conditions=[searchBar text];
    [shopListController setRecieveDictionary:dictionary];
    [self.navigationController pushViewController: shopListController animated:YES];
}

- (void)viewDidDisappear:(BOOL)animated{
    searchBarCustom.text=@"";
    [searchBarCustom resignFirstResponder];
}

-(void)viewDidUnload{
    self.appDelegate=nil;
    self.searchBarCustom=nil;
    self.directBtn=nil;
    self.detailBtn=nil;
self.directSearchView=nil;
self.detailSearchView=nil;
self.address=nil;
self.time=nil;
self.isSelling=nil;
self.addTestData=nil;
self.typeTestData=nil;
self.timeTestData=nil;
    [super viewDidUnload];
}

@end
